<template>
  <div class="login-container">
    <el-container>
      <el-header style="background-color: #67C23A; color: white;">
        <div style="text-align: center; font-size: 25px; font-weight: bolder">
          <i class="el-icon-s-promotion" style="margin-right: 25px"></i>
          广东龙舟文化推广平台
        </div>
      </el-header>
      <el-main style="background-color: #f0f9eb;">
        <el-card class="login-module">
          <div slot="header" class="clearfix">
            <span style="text-align: center; font-size: 20px; font-family: 'Microsoft YaHei'">
              <p><i class="el-icon-s-flag" style="margin-right: 18px; color: #67C23A;"></i>用户登录</p>
            </span>
          </div>
          <div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="用户类型" prop="type" class="user-type-item">
                <el-radio-group v-model="ruleForm.type" @change="handleTypeChange">
                  <el-radio label="team" border>龙舟队</el-radio>
                  <el-radio label="organizer" border>赛事主办方</el-radio>
                  <el-radio label="audience" border>观众</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username" prefix-icon="el-icon-user"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" placeholder="请输入6-14位密码" show-password prefix-icon="el-icon-lock"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="submitForm('ruleForm')">登录</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
                <el-button type="text" @click="$router.push('/register')">没有账号？去注册</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
        type: null,
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '用户名长度在2到20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 14, message: '密码长度在6到14个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
      }
    };
  },
  methods: {
    handleTypeChange() {
      // 重置表单
      this.ruleForm.username = '';
      this.ruleForm.password = '';
    },
    
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.type === 'organizer') {
            this.handleOrganizerLogin();
          } else if (this.ruleForm.type === 'team') {
            this.handleTeamLogin();
          } else if (this.ruleForm.type === 'audience') {
            this.handleAudienceLogin();
          } else {
            this.$message.error('无效的用户类型');
          }
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    
    handleOrganizerLogin() {
      axios.post("http://localhost:10086/organizer/loginByname", null, {
        params: {
          organizerName: this.ruleForm.username,
          password: this.ruleForm.password
        }
      })
      .then(response => {
        if (response.data && response.data.code === 200) {
          const organizer = response.data.data;
          this.$store.dispatch('login', {
            token: 'true',
            type: 'organizer',
            id: organizer.organizerId,
            name: organizer.organizerName
          });
          
          sessionStorage.setItem("token", 'true');
          sessionStorage.setItem("type", 'organizer');
          sessionStorage.setItem("userId", organizer.organizerId);
          sessionStorage.setItem("userName", organizer.organizerName);
          
          this.$message.success(`登录成功，欢迎 ${organizer.organizerName}!`);
          this.$router.push('/organizer');
        } else {
          this.$message.error(response.data?.message || '账号或密码错误');
        }
      })
      .catch(error => {
        console.error('主办方登录失败:', error);
        this.$message.error(error.response?.data?.message || '登录失败，请稍后重试');
      });
    },
    
    handleTeamLogin() {
      axios.post("http://localhost:10086/team/loginByname", null, {
        params: {
          teamName: this.ruleForm.username,
          password: this.ruleForm.password
        }
      })
      .then(response => {
        if (response.data && response.data.code === 200) {
          const team = response.data.data;
          
          this.$store.dispatch('login', {
            token: 'true',
            type: 'team',
            id: team.teamId,
            name: team.teamName
          });
          
          sessionStorage.setItem("token", 'true');
          sessionStorage.setItem("type", 'team');
          sessionStorage.setItem("userId", team.teamId);
          sessionStorage.setItem("userName", team.teamName);
          
          this.$message.success(`登录成功，欢迎 ${team.teamName}!`);
          this.$router.push('/team');
        } else {
          this.$message.error(response.data?.message || '账号或密码错误');
        }
      })
      .catch(error => {
        console.error('队伍登录失败:', error);
        this.$message.error(error.response?.data?.message || '登录失败，请稍后重试');
      });
    },
    
    handleAudienceLogin() {
      axios.post("http://localhost:10086/audience/loginByname", null, {
        params: {
          audienceName: this.ruleForm.username,
          password: this.ruleForm.password
        }
      })
      .then(response => {
        if (response.data && response.data.code === 200) {
          const audience = response.data.data;
          
          this.$store.dispatch('login', {
            token: 'true',
            type: 'audience',
            id: audience.audienceId,
            name: audience.audienceName
          });
          
          sessionStorage.setItem("token", 'true');
          sessionStorage.setItem("type", 'audience');
          sessionStorage.setItem("userId", audience.audienceId);
          sessionStorage.setItem("userName", audience.audienceName);
          
          this.$message.success(`登录成功，欢迎 ${audience.audienceName }!`);
          this.$router.push('/audience');
        } else {
          this.$message.error(response.data?.message || '账号或密码错误');
        }
      })
      .catch(error => {
        console.error('观众登录失败:', error);
        this.$message.error(error.response?.data?.message || '登录失败，请稍后重试');
      });
    },
    
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style>
/* 样式保持不变 */
.login-container {
  height: 100vh;
  background-color: #f0f9eb;
}

.login-module {
  margin: 60px auto;
  text-align: center;
  width: 500px;
  border: 1px solid #67C23A;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(103, 194, 58, 0.2);
}

.el-header {
  line-height: 60px;
}

.user-type-item {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #EBEEF5;
}

.el-radio.is-bordered {
  margin: 5px;
  border-color: #67C23A;
}

.el-radio.is-bordered.is-checked {
  border-color: #67C23A;
  background-color: #f0f9eb;
}

.el-button--success {
  background-color: #67C23A;
  border-color: #67C23A;
}

.el-button--success:hover {
  background-color: #5daf34;
  border-color: #5daf34;
}

.el-card__header {
  border-bottom: 1px solid #67C23A;
  background-color: #fff;
}

.el-card__body {
  background-color: #fff;
}

.el-form-item__label {
  color: #67C23A;
  font-weight: bold;
}

.el-input__inner:focus {
  border-color: #67C23A;
}

.el-input__inner::placeholder {
  color: #C0C4CC;
  font-size: 14px;
}
</style>